package com.airnewslinkosky.ticket.ui.flight;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.airnewslinkosky.ticket.R;
import com.airnewslinkosky.ticket.model.AirEXPaymentResult;
import com.airnewslinkosky.ticket.model.FlightInfo;
import com.airnewslinkosky.ticket.model.ItineraryInfo;
import com.airnewslinkosky.ticket.model.SearchFlight;
import com.airnewslinkosky.ticket.model.TotalOrderInfoResult;
import com.airnewslinkosky.ticket.net.WebAccessor;
import com.airnewslinkosky.ticket.pay.util.AlixId;
import com.airnewslinkosky.ticket.pay.util.BaseHelper;
import com.airnewslinkosky.ticket.pay.util.MobileSecurePayHelper;
import com.airnewslinkosky.ticket.pay.util.MobileSecurePayer;
import com.airnewslinkosky.ticket.pay.util.ResultChecker;
import com.airnewslinkosky.ticket.ui.BaseActivity;
import com.airnewslinkosky.ticket.ui.PayResult;
import com.airnewslinkosky.ticket.util.AddrUtil;
import com.airnewslinkosky.ticket.util.Constants;
import com.airnewslinkosky.ticket.util.FlyUtil;
import com.mobclick.android.MobclickAgent;

public class CreditCard extends BaseActivity{

	public  final int DIALOG_PPPTYPE_LIST = 10;
	public  final int NET_ERROR=6;
	public  final int PAY_ERROR=7;
	public  final int PAY_SUCCESS=0;
	public  final int PLOIC_ERROR = -36000;//航班政策数据变更
	
	public static boolean isNowPay;//是否马上支付
	public static  String ticketType = "0";//默认单程
	
	public static FlightInfo flight;
	public static FlightInfo returnFlight;
	public static String isItinerary;//是否需要行程单
	public static String isInsurance;
	public static List<Map<String,String>> passengerList = new ArrayList<Map<String,String>>();
	public static List<Map<String,String>> contactList = new ArrayList<Map<String,String>>();
	public static List<Map<String,String>> itineraryList = new ArrayList<Map<String,String>>();
	public static ItineraryInfo itineraryInfo = new ItineraryInfo();
	
	public static SearchFlight searchFlight;
	public static TotalOrderInfoResult totalOrderInfoResult;
	public static String sumPriceFormat;
	private Button backBut;
	public SimpleAdapter sa;
	public ListView lv;
	public Button mBtnBack,mBtnNext,passengerSaveBut;
	List<Map<String, String>> data = new ArrayList<Map<String, String>>();

	private ProgressDialog progressDialog = null;
	
	private ProgressDialog mProgress = null;
	private FlyUtil flyUtil;
	private AddrUtil addrUtil;
	public Handler myHandler;

	private TextView  order_no, order_date,course;
	private TextView  t_order_no, t_order_date,t_course;
	
	private RelativeLayout flightPay;
	
	private RelativeLayout t_order_info_type2,t_course_layout,t_order_info_type3,t_order_info_lay;
	
	private int postion=0;
    private TextView flightTotalPriceValue;
    private SharedPreferences sp;
    private String ASToken;
    
    private Toast toast;
    
    private boolean isPaySuccess = false;
    
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.order_pay);
		// 删除窗口背景
        getWindow().setBackgroundDrawable(null);
		activityList.add(this);
		
		//要是没有安装支付宝插件，提示用户下载安装
		MobileSecurePayHelper mspHelper = new MobileSecurePayHelper(this);
		mspHelper.detectMobile_sp();
		
		flyUtil = new FlyUtil(this);
		addrUtil = new AddrUtil(this);
		
		flightTotalPriceValue =  (TextView)findViewById(R.id.flight_total_price_value);
		flightTotalPriceValue.setText(sumPriceFormat + "元");
		
		backBut = (Button)findViewById(R.id.backBut);
		
		initData();
    	flightPay =  (RelativeLayout)findViewById(R.id.flight_pay);
    	
		OnClickListener b_ocl= new OnClickListener() { 
	    	public void onClick(View v) { 
	    		switch (v.getId()) {
		    		case R.id.backBut:
		    			Intent intent3 = new Intent();
		    			intent3.setClass(CreditCard.this, FlyOrderDetail.class);
		    			FlyOrderDetail.flight = flight;
						FlyOrderDetail.returnFlight = returnFlight;
						FlyOrderDetail.passengerList = passengerList;
						FlyOrderDetail.contactList = contactList;
						FlyOrderDetail.isItinerary = isItinerary;
						FlyOrderDetail.isInsurance = isInsurance;
						FlyOrderDetail.itineraryList = itineraryList;
						FlyOrderDetail.searchFlight = searchFlight;
		    			startActivity(intent3);
		    			break;
		    		case R.id.flight_pay:
		    			airEXPayment();
		    			break;
	    		}
	    	}
		};
		
		backBut.setOnClickListener(b_ocl);
		flightPay.setOnClickListener(b_ocl);
		myHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case NET_ERROR:
					toast = Toast.makeText(CreditCard.this, "网络超时，连接失败", Toast.LENGTH_LONG);
					toast.setGravity(Gravity.CENTER, 0, 0);
					toast.show();
					break;
				case PAY_ERROR:
					BaseHelper.showDialog(
							CreditCard.this,
							"支付失败",
							(String)msg.obj,
							android.R.drawable.ic_dialog_alert);
					break;
				case PAY_SUCCESS:
//					toast = Toast.makeText(CreditCard.this, "已经成功支付！", Toast.LENGTH_LONG);
//					toast.setGravity(Gravity.CENTER, 0, 0);
//					toast.show();
					break;
				case PLOIC_ERROR:
					Intent intentDirectOut = new Intent();
					intentDirectOut.setClass(CreditCard.this, FlyOrderDetailRebuild.class);
					FlyOrderDetailRebuild.flight = flight;
					FlyOrderDetailRebuild.returnFlight = returnFlight;
					FlyOrderDetailRebuild.passengerList = passengerList;
					FlyOrderDetailRebuild.contactList = contactList;
					FlyOrderDetailRebuild.isItinerary = isItinerary;
					FlyOrderDetailRebuild.isInsurance = isInsurance;
					FlyOrderDetailRebuild.itineraryList = itineraryList;
					FlyOrderDetailRebuild.searchFlight = searchFlight;
					FlyOrderDetailRebuild.totalOrderInfoResult = totalOrderInfoResult;
					startActivity(intentDirectOut);
					break;
				}
				super.handleMessage(msg);
			}
		};
		
		//要是马上支付，就直接调用。
		if(isNowPay){
			airEXPayment();
		} 
	}
	
	private void initData() {
		order_no = (TextView) findViewById(R.id.order_no);
		order_date = (TextView) findViewById(R.id.order_date);
		course =  (TextView) findViewById(R.id.course); 
    	
		order_no.setText(flyUtil.getName(flight.airline)+ " " + flight.flightNo);
		order_date.setText(flight.departureTime);
		course.setText(addrUtil.getCityByCode(flight.departure).getCity() + "→" + addrUtil.getCityByCode(flight.arrival).getCity());
		
		if(returnFlight!=null){
			t_order_info_type2 = (RelativeLayout)findViewById(R.id.t_order_info_type2);
			t_course_layout =  (RelativeLayout)findViewById(R.id.t_course_layout);
			t_order_info_type3  = (RelativeLayout)findViewById(R.id.t_order_info_type3);
			t_order_info_lay  = (RelativeLayout)findViewById(R.id.t_order_info_lay);
			
			t_order_info_lay.setVisibility(View.VISIBLE);
			t_order_info_type2.setVisibility(View.VISIBLE);
			t_course_layout.setVisibility(View.VISIBLE);
			t_order_info_type3.setVisibility(View.VISIBLE);
			
			t_order_no = (TextView) findViewById(R.id.t_order_no);
			t_order_date = (TextView) findViewById(R.id.t_order_date);
			t_course =  (TextView) findViewById(R.id.t_course); 
	    	
			t_order_no.setText(flyUtil.getName(returnFlight.airline)+ " " + returnFlight.flightNo);
			t_order_date.setText(returnFlight.departureTime);
			t_course.setText(addrUtil.getCityByCode(returnFlight.departure).getCity() + "→" + addrUtil.getCityByCode(returnFlight.arrival).getCity());
		}
	}
	
	//向接口发送支付请求；接口返回支付宝相关的信息，这些信息原封提交给支付宝。
	private void airEXPayment() {
		progressDialog = ProgressDialog.show(this, "请稍等...", "正在进行对支付宝发起申请...",true);
		final Thread thread = new Thread() {
			public void run() {
		        try {
//		        	sp = getSharedPreferences("UserInfoB2C", Context.MODE_WORLD_WRITEABLE | Context.MODE_WORLD_READABLE);
//			        String userIdLogin = sp.getString("userId", null);
//			        String userPwd =  sp.getString("userPwd", null);
//			        ASToken = sp.getString("ASToken", "");
			        
			        String userIdLogin = Constants.USERID;
			        String userPwd =  Constants.USERPWD;
			        String asToken =  Constants.ASToken;
			        
			        AirEXPaymentResult as = WebAccessor.airEXPayment(userIdLogin,userPwd,asToken,totalOrderInfoResult.OrderNO,sumPriceFormat,addrUtil.getCityByCode(flight.departure).getCity() + "→" + addrUtil.getCityByCode(flight.arrival).getCity(),ticketType);
					if (progressDialog.isShowing()) {
						if("-36000".equals(as.Result)){
							Message msg = new Message();
							msg.what = PLOIC_ERROR;
							msg.obj = as.ErrorDescription;
							myHandler.sendMessage(msg);
						} else if("0".equals(as.Result)){
							Message msg = pay(as.PostInfo);
							myHandler.sendMessage(msg);
						}else{
							Message msg = new Message();
							msg.what = PAY_ERROR;
							msg.obj = as.ErrorDescription;
							myHandler.sendMessage(msg);
						}
						progressDialog.dismiss();
					}
		        } catch (Exception e) {
					e.printStackTrace();
				}
			}
		};
		progressDialog.setCancelable(true);
		thread.start();
	}
	
	//调用支付宝插件接口，提交支付申请操作。
	private Message pay(String postInfo) {
		Message msg = new Message();
		try {
			// start the pay.
			MobileSecurePayer msp = new MobileSecurePayer();
			boolean bRet = msp.pay(postInfo, mHandler, AlixId.RQF_PAY, this);

			if (bRet) {
				// show the progress bar to indicate that we have started
				// paying.
				closeProgress();
				progressDialog = BaseHelper.showProgress(this, null, "正在支付", false,
						true);
				msg.what = PAY_SUCCESS;
			} else {
				;
			}
		} catch (Exception ex) {
//			msg.what = PAY_ERROR;
//			msg.obj = "支付失败，原因：" + ex.getMessage();
			;
		}
		return msg;
	}
	


	//
	// the handler use to receive the pay result.
	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			try {
				String strRet = (String) msg.obj;

				switch (msg.what) {
				case AlixId.RQF_PAY: {
					//
					closeProgress();

					BaseHelper.log("CreditCard", strRet);

					try {
						String memo = "memo=";
						int imemoStart = strRet.indexOf("memo=");
						imemoStart += memo.length();
						int imemoEnd = strRet.indexOf(";result=");
						memo = strRet.substring(imemoStart, imemoEnd);

						ResultChecker resultChecker = new ResultChecker(strRet);

						int retVal = resultChecker.checkSign();
						System.out.println("支付后的状态：" + retVal);
						if (retVal == ResultChecker.RESULT_CHECK_SIGN_FAILED) {
							BaseHelper.showDialog(
									CreditCard.this,
									"提示",
									getResources().getString(
											R.string.check_sign_failed),
									android.R.drawable.ic_dialog_alert);
						} else if (retVal == ResultChecker.RESULT_CHECK_SIGN_SUCCEED) {
							BaseHelper.showDialog(CreditCard.this, "提示", memo,
									R.drawable.infoicon);
							isPaySuccess = true;
							Intent intent = new Intent();
							intent.setClass(CreditCard.this, PayResult.class);
							PayResult.isPaySuccess = isPaySuccess;
							startActivity(intent);
						} else if(retVal == ResultChecker.RESULT_INVALID_PARAM) {
							isPaySuccess = false;
							Intent intent = new Intent();
							intent.setClass(CreditCard.this, PayResult.class);
							PayResult.isPaySuccess = isPaySuccess;
							startActivity(intent);
						}
						
					} catch (Exception e) {
						e.printStackTrace();

						BaseHelper.showDialog(CreditCard.this, "提示", strRet,
								R.drawable.infoicon);
					}
				}
					break;
				}

				super.handleMessage(msg);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};

	//
	// the OnCancelListener for lephone platform.
	public static class AlixOnCancelListener implements
			DialogInterface.OnCancelListener {
		Activity mcontext;

		public AlixOnCancelListener(Activity context) {
			mcontext = context;
		}

		public void onCancel(DialogInterface dialog) {
			mcontext.onKeyDown(KeyEvent.KEYCODE_BACK, null);
		}
	}

	//
	// close the progress bar
	void closeProgress() {
		try {
			if (mProgress != null) {
				mProgress.dismiss();
				mProgress = null;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void onResume() {     
		super.onResume();     
		MobclickAgent.onResume(this); 
	}  
	
	public void onPause() {     
		super.onPause();     
		MobclickAgent.onPause(this); 
	}  
}


